#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import os, sys, time, hashlib, base64, json


def gen_suffix(filename):
    for i in ["gif", "jpg", "jpeg", "png", "bmp"]:
        if ("." + i) in filename:
            return i

    ridx = filename.rfind(".")
    if (ridx >= 0):
        aaa = filename[ridx + 1:]
        if (len(aaa) <= 5):
            return aaa
    return "png"


def gen_filepath(filename):
    fname_suf = gen_suffix(filename)

    with open(filename, "rb") as f:
        t = f.read()
        fname = hashlib.md5(t).hexdigest()
        fcontext = base64.b64encode(t).decode()

    if fname is None:
        import random
        fname = "%s_%s" % (int(time.time() * 1000), int(random.random() * 1000))

    min_time = time.strftime("%Y%m")

    return os.path.join("notes", min_time, fname + "." + fname_suf), fcontext


def upload_img(filename):
    storepath, storecontent = gen_filepath(filename)

    request_url = base_url.format(owner=config['owner'], repo=config['repo'], path=storepath)
    preview_url = raw_url.format(owner=config['owner'], repo=config['repo'], path=storepath)

    data = {
        "access_token": config['access_token'],
        "content": storecontent,
        "message": "Upload File : " + storepath,
    }

    try:
        import urllib3
        http = urllib3.PoolManager()
        resp = http.request("POST", request_url, data)
        if resp.status >= 200 and resp.status <= 300:
            return preview_url
        else:
            print(resp.data.decode())
        return
    except:
        pass

    import urllib.request
    import urllib.parse

    postdata = bytes(json.dumps(data), "utf-8")
    request = urllib.request.Request(request_url, postdata, headers={
        "Content-Type": "application/json"
    })
    resp = urllib.request.urlopen(request)

    if resp.status >= 200 and resp.status <= 300:
        return preview_url
    else:
        print(resp.read().decode("utf-8"))


pyfile = os.path.abspath(__file__)
base_url = "https://gitee.com/api/v5/repos/{owner}/{repo}/contents/{path}"
raw_url = "https://gitee.com/{owner}/{repo}/raw/master/{path}"

config = {
    "owner": "heavenick",
    "repo": "noteimg",
    "access_token": "f2473364a4cfee6f61035a79fed2e0dd"
}

result_url = []
for arg in sys.argv:
    target_file = os.path.abspath(arg)

    if (pyfile == target_file or not os.path.exists(target_file)):
        continue

    # print(gen_filepath(target_file))
    rurl = upload_img(target_file)
    if rurl:
        result_url.append(rurl)

if len(result_url) > 0:
    print("Upload Success:")
    for url in result_url:
        print(url)
else:
    print("Upload Failed")
